package com.zcsy.manage.web.mall;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zcsy.commons.constants.Constants;
import com.zcsy.commons.model.RequestConstants;
import com.zcsy.commons.model.RequestJson;
import com.zcsy.commons.unique.UniqueNumberUtils;
import com.zcsy.commons.util.DateUtils;
import com.zcsy.manage.model.base.CommonImg;
import com.zcsy.manage.model.mall.CategoryAttr;
import com.zcsy.manage.model.mall.GoodsCategory;
import com.zcsy.manage.model.mall.GoodsInfo;
import com.zcsy.manage.model.mall.GoodsSpecification;
import com.zcsy.manage.model.mall.GoodsSpecificationAttr;
import com.zcsy.manage.model.mall.vo.GoodsAttrInfo;
import com.zcsy.manage.model.system.Dict;
import com.zcsy.manage.model.system.User;
import com.zcsy.manage.persistence.weixin.StringUtil;
import com.zcsy.manage.service.base.ICommonImgService;
import com.zcsy.manage.service.mall.ICategoryAttrService;
import com.zcsy.manage.service.mall.IGoodsCategoryService;
import com.zcsy.manage.service.mall.IGoodsInfoService;
import com.zcsy.manage.service.mall.IGoodsSpecificationService;
import com.zcsy.manage.service.system.IDictService;
import com.zcsy.manage.web.common.LogUtils;

/**
 * @Title: GoodsInfoController.java @Package： com.zcsy.manage.web.mall
 * @Description: 商品信息controller层
 *
 * @author caiyinli 13277030520@163.com
 * @Copyright: 2015 武汉中财数元信息技术有限公司 All rights reserved.
 * @date 2016年4月26日
 * @version 1.0
 * @see JDK1.7.0_75
 * @since
 */

@Controller
@RequestMapping(value = "/goodsInfo")
public class GoodsInfoController {

    @Autowired
    private IGoodsInfoService goodsInfoService;

    @Autowired
    private IGoodsCategoryService goodsCategoryService;

    @Autowired
    private IDictService dictService;

    @Autowired
    private ICategoryAttrService categoryAttrService;

    @Autowired
    private IGoodsSpecificationService goodsSpecificationService;

    @Autowired
    private ICommonImgService commonImgService;

    private static final int GOODS_STATE = -1; // 商品初始状态（包括上架和下架）
    private static final int INIT_STATE = 1; // 新增商品初始状态（下架）
    // private static final int PAGE_SIZE = 7; //页面数据条数

    /**
     * @description 返回商品列表信息
     * @param pNo
     *            页数
     * @param pSize
     *            分页大小
     * @param name
     *            商品名称
     * @param state
     *            商品状态
     * @param goodsType
     *            商品种类 String 商品列表路径
     * @author chenxin
     * @date 2016年8月26日下午3:15:40
     */
    @RequestMapping(value = "goodsInfoList", method = RequestMethod.GET)
    public String goodsInfoList(Model model, Integer pNo, Integer pSize, String name, Integer state, Integer goodsType,
            HttpServletRequest req) {

        if (pNo == null) {
            pNo = Constants.PAGE_NO;
        }

        Integer pageSize;
        if (pSize == null) {
            pageSize = Constants.PAGE_SIZE;
        } else {
            switch (pSize) {
            case 0:
                pageSize = Constants.PAGE_SIZE;
                break;
            case 1:
                pageSize = Constants.PAGE_SIZE_TWENTY;
                break;
            case 2:
                pageSize = Constants.PAGE_SIZE_FIFTY;
                break;
            default:
                pageSize = Constants.PAGE_SIZE;
                break;
            }
        }

        // 此处添加PageHelper将会走拦截器，进行分页，分页方法只针对紧跟着PageHelper的查询方法有效
        PageHelper.startPage(pNo, pageSize);

        GoodsInfo goodsInfo = new GoodsInfo();

        if (StringUtils.isNotEmpty(name)) {
            goodsInfo.setName(name);
        }

        if (state == null) {
            state = GOODS_STATE;
        }
        if (goodsType != null) {
            goodsInfo.setType(goodsType);
        }
        goodsInfo.setState(state);

        List<GoodsInfo> goodsInfos = goodsInfoService.getGoodsInfoByKeyword(goodsInfo);
        PageInfo<GoodsInfo> info = new PageInfo<GoodsInfo>(goodsInfos);

        model.addAttribute("goodsInfo", info);
        model.addAttribute("currentPage", pNo);
        model.addAttribute("pSize", pSize);
        model.addAttribute("name", name);
        model.addAttribute("goodsType", goodsType);
        model.addAttribute("state", state);

        List<Dict> pageSizes = dictService.getDictFromCache("pageSize");
        model.addAttribute("pageSizes", pageSizes);

        return "mall/goodsInfo/goodsInfoList";
    }

    /**
     * @description 返回商品新增或编辑页面
     * @param id
     *            商品主键
     * @param goodsType
     *            商品种类
     * @date 2016年8月26日下午3:16:39
     */
    @RequestMapping(value = "editGoodsInfo", method = RequestMethod.GET)
    public String editGoodsInfo(Model model, String id, int goodsType) {
        try {
            if (String.valueOf(Constants.STATE_DISABLED).equals(id)) {
                model.addAttribute("type", Constants.SAVE_TYPE);
            } else {
                GoodsInfo goodsInfo = goodsInfoService.getGoodsInfoByPrimaryKey(id);
                if (goodsInfo != null) {
                    model.addAttribute("type", Constants.EDIT_TYPE);
                    model.addAttribute("goodsInfo", goodsInfo);
                    GoodsCategory goodsCategory = goodsCategoryService
                            .getGoodsCategoryById(goodsInfo.getGoodsCategoryId());
                    model.addAttribute("goodsCategory", goodsCategory);
                    model.addAttribute("secondCategory",
                            goodsCategoryService.getGoodsCategoryByParentId(goodsCategory.getParentId()));

                    /*
                     * if(goodsInfo.getKeyword() != null){ String[] key =
                     * goodsInfo.getKeyword().split("\\,"); String keyword =
                     * StringUtils.join(key, "|"); model.addAttribute("keyword",
                     * keyword); }
                     */

                    // 根据分类id获取所有的商品分类属性
                    // List<CategoryAttr> categoryAttrs =
                    // categoryAttrService.selectByCategoryId(goodsInfo.getGoodsCategoryId());

                    // 商品规格信息
                    List<GoodsSpecification> goodsSpecList = goodsSpecificationService
                            .getGoodsSpecificationDetailByGoodsId(goodsInfo.getId());
                    model.addAttribute("goodsSpecList", goodsSpecList);

                    // 商品对应规格属性
                    List<String> attrNames = new ArrayList<>();
                    if (null != goodsSpecList && goodsSpecList.size() > 0) {
                        for (GoodsSpecificationAttr attr : goodsSpecList.get(0).getGoodsSpecificationAttrs()) {
                            attrNames.add(attr.getAttrName());
                        }
                    }
                    model.addAttribute("attrNames", attrNames);

                }
            }

            // 获取商品banner图
            List<CommonImg> imgs = commonImgService.selectImgsByObjIdAndObjType(id, Constants.IMG_GOODS_BANNER);
            model.addAttribute("imgs", imgs);

            // 获取所有一级商品分类
            model.addAttribute("firstCategory", goodsCategoryService.getGoodsCategoryByLevel(1));
            model.addAttribute("goodsType", goodsType);

        } catch (Exception e) {
        }
        return "mall/goodsInfo/goodsInfoEdit";
    }

    /**
     * @description 商品信息保存方法
     * @date 2016年8月26日下午3:17:41
     */
    @RequestMapping(value = "saveOrUpdateGoodsInfo", method = RequestMethod.POST)
    @ResponseBody
    public RequestJson saveOrUpdateGoodsInfo(@RequestBody List<GoodsAttrInfo> infoList, HttpServletRequest request,
            HttpServletResponse response) {
        RequestJson result = new RequestJson();
        User user = (User) request.getSession().getAttribute(RequestConstants.USER_SESSION_ID);
        SimpleDateFormat sdf = new SimpleDateFormat("yy-MM-dd HH:mm:ss"); 
        try {
            GoodsAttrInfo info = infoList.get(0);
            GoodsInfo record = new GoodsInfo();

            if (info.getGoodsId() != "" && !"0".equals(info.getGoodsId())) {
                record = goodsInfoService.getGoodsInfoByPrimaryKey(info.getGoodsId());
            }
            record.setName(info.getGoodsName());
            record.setGoodsCategoryId(info.getSecondCategory());
            record.setStock(Integer.parseInt(info.getStockAmount()));
            record.setType(Integer.parseInt(info.getGoodsType()));
            if (info.getPrice() != null) {
                record.setPrice(new BigDecimal(info.getPrice()));
            }
            if (info.getIntegralNum() != null) {
                record.setIntegralNum(Integer.parseInt(info.getIntegralNum()));
            }
            if (!StringUtil.isEmptyString(info.getMarketPrice())) {
                record.setMarketPrice(new BigDecimal(info.getMarketPrice()));
            } else {
                record.setMarketPrice(BigDecimal.ZERO);
            }

            record.setUnit(info.getUnit());
            record.setKeyword(info.getKeyword());
            if (!StringUtil.isEmptyString(info.getIsRecommend())) {
                record.setIsRecommend(Integer.parseInt(info.getIsRecommend()));
            }
            record.setDetail(info.getContainer());
            record.setSort(Integer.parseInt(info.getSort()));
            record.setUserAccount(user.getLoginname());

            if (info.getStartTime() != null) {
                record.setSecKillStarttime(info.getStartTime());
            }
            if (info.getEndTime() != null) {
                record.setSecKillEndtime(info.getEndTime());
            }

            record.setLogo(info.getImageLogoUrl());

            if (info.getGoodsId() != "" && !"0".equals(info.getGoodsId())) {
                record.setUpdateTime(DateUtils.getFmtDate());
                goodsInfoService.updateGoodsInfoAndSpec(record, infoList);
                LogUtils.insertLog("用户编辑商品信息", user.getId(), request);

            } else {
                record.setId(UniqueNumberUtils.get18UniqueNumber());
                record.setSendTime(DateUtils.getFmtDate());
                record.setState(INIT_STATE);
                // record.setCategoryAttrs(categoryAttrService.selectByCategoryId(info.getSecondCategory()));
                // record.setGoodsSpecifications(goodsSpecificationService.getGoodsSpecificationByGoodsId(info.getGoodsId()));
                goodsInfoService.insert(record, infoList);
                LogUtils.insertLog("用户新增商品信息", user.getId(), request);

            }

            List<CommonImg> imgs = commonImgService.selectImgsByObjIdAndObjType(record.getId(),
                    Constants.IMG_GOODS_BANNER);

            if (CollectionUtils.isNotEmpty(imgs)) {
                for (CommonImg commonImg : imgs) {
                    commonImgService.deleteById(commonImg.getId());
                }
            }

            CommonImg commonImg = new CommonImg();
            for (String item : info.getImgArr()) {
                commonImg.setId(UniqueNumberUtils.get18UniqueNumber());
                commonImg.setUrl(item);
                commonImg.setObjId(record.getId());
                commonImg.setObjType(Constants.IMG_GOODS_BANNER);
                commonImgService.insert(commonImg);
            }

            result.setObj(record);
        } catch (Exception e) {
            result.setSuccess(false);
            result.setMsg("操作异常");
        }

        return result;
    }

    /**
     * @description 商品状态更新
     * @date 2016年8月26日下午3:18:59
     */
    @RequestMapping(value = "updateState", method = RequestMethod.GET)
    @ResponseBody
    public RequestJson updateState(String id, int state, HttpServletRequest req) {
        RequestJson result = new RequestJson();
        User user = (User) req.getSession().getAttribute(RequestConstants.USER_SESSION_ID);

        try {
            int flag = Constants.SQL_RESULT_ERROR;
            flag = goodsInfoService.updateGoodsStateByMap(id, state);
            if (flag == Constants.SQL_RESULT_SUCCESS) {
                result.setSuccess(true);
                LogUtils.insertLog("用户更新商品状态", user.getId(), req);

            }
        } catch (Exception e) {
            result.setMsg("操作失败");
            result.setSuccess(false);
        }
        GoodsInfo goodsInfo = goodsInfoService.getGoodsInfoByPrimaryKey(id);
        result.setObj(goodsInfo);
        return result;
    }

    /**
     * @description 删除商品
     * @date 2016年8月26日下午3:20:06
     */
    @RequestMapping(value = "deleteGoodsInfo", method = RequestMethod.POST)
    @ResponseBody
    public RequestJson deleteGoodsInfo(String goodsIDs, HttpServletRequest req) {

        RequestJson result = new RequestJson();
        User user = (User) req.getSession().getAttribute(RequestConstants.USER_SESSION_ID);

        try {
            String ids[] = goodsIDs.split("\\,");
            for (int i = 0; i < ids.length; i++) {
                // 逻辑删除，修改商品状态为2
                goodsInfoService.deleteByUpdateState(ids[i]);
            }
            result.setSuccess(true);
            LogUtils.insertLog("用户删除商品状态", user.getId(), req);

        } catch (NumberFormatException e) {
            result.setSuccess(false);
            result.setMsg("操作失败");
        }
        return result;
    }

    /**
     * @Description 通过商品分类id获取分类属性集合<br>
     * 
     * @param categoryId
     *            商品分类id
     * @param req
     *            用户请求
     * @return 分类属性集合
     * @author caiyinli 13277030520@163.com
     * @date 2016年5月12日
     * @see
     */
    @RequestMapping(value = "getGoodsAttrByCategoryId", method = RequestMethod.POST)
    @ResponseBody
    public RequestJson getGoodsAttrByCategoryId(String categoryId, HttpServletRequest req) {

        RequestJson result = new RequestJson();

        try {
            List<CategoryAttr> goodsCategories = categoryAttrService.selectByCategoryId(categoryId);
            for (CategoryAttr item : goodsCategories) {
                item.setCategoryAttrValues(categoryAttrService.selectByAttrId(item.getId()));
            }
            result.setSuccess(true);
            result.setObj(JSONArray.fromObject(goodsCategories).toString());
        } catch (NumberFormatException e) {
            result.setSuccess(false);
            result.setMsg("操作失败");
        }
        return result;
    }

    /**
     * @Description 实现商品置顶功能，积分商品修改积分商品的sort、秒杀商品修改秒杀商品的sort来置顶，并且更新修改时间<br>
     * 
     * @param id
     *            商品id
     * @param req
     *            用户请求
     * @return
     * @author caiyinli 13277030520@163.com
     * @date 2016年6月3日
     * @see
     */
    @RequestMapping(value = "updateSort", method = RequestMethod.GET)
    @ResponseBody
    public RequestJson updateSort(String id, HttpServletRequest req) {
        RequestJson result = new RequestJson();
        User user = (User) req.getSession().getAttribute(RequestConstants.USER_SESSION_ID);

        try {
            if (id != null) {
                String updateTime = DateUtils.getFmtDate();
                goodsInfoService.updateSort(id, updateTime);
                LogUtils.insertLog("用户置顶商品信息", user.getId(), req);

            } else {
                result.setMsg("该商品不存在！");
                result.setSuccess(false);
            }
        } catch (Exception e) {
            result.setMsg("操作失败");
            result.setSuccess(false);
        }

        return result;
    }

    /**
     * @Description 获取特定店铺状态正常的商品
     * @param shopId
     *            店铺id
     * @return 商品列表
     * @author liuying 1075817474@qq.com
     * @date 2016年9月12日
     * @see
     */
    @RequestMapping(value = "/getGoodsInfoByShopId", method = RequestMethod.GET)
    @ResponseBody
    public RequestJson getGoodsInfoByShopId(String shopId) {
        RequestJson result = new RequestJson();
        try {
            List<GoodsInfo> GoodsInfoList = goodsInfoService.getGoodsInfoByShopId(shopId);
            result.setObj(GoodsInfoList);
        } catch (Exception e) {
            result.setMsg("操作异常");
            result.setSuccess(false);
        }
        return result;
    }

    /**
     * @description 展示商品的详情
     * @param id 商品的主键id
     * @return String
     * @author chenxin
     * @date 2016年9月14日上午8:55:52
     */
    @RequestMapping(value = "/showDetail", method = RequestMethod.GET)
    public String showDetail(Model model, String id) {
        try {

            GoodsInfo goodsInfo = goodsInfoService.getGoodsInfoByPrimaryKey(id);
            if (goodsInfo != null) {
                //商品类型：1正常商品2积分商品3秒杀商品
                model.addAttribute("goodsType", goodsInfo.getType());
                //商品基本信息详情
                model.addAttribute("goodsInfo", goodsInfo);
                //商品分类信息
                GoodsCategory goodsCategory = goodsCategoryService.getGoodsCategoryById(goodsInfo.getGoodsCategoryId());
                model.addAttribute("goodsCategory", goodsCategory);
                model.addAttribute("secondCategory",
                        goodsCategoryService.getGoodsCategoryByParentId(goodsCategory.getParentId()));
                // 商品规格信息
                List<GoodsSpecification> goodsSpecList = goodsSpecificationService
                        .getGoodsSpecificationDetailByGoodsId(goodsInfo.getId());
                model.addAttribute("goodsSpecList", goodsSpecList);
                // 商品对应规格属性
                List<String> attrNames = new ArrayList<>();
                if (null != goodsSpecList && goodsSpecList.size() > 0) {
                    for (GoodsSpecificationAttr attr : goodsSpecList.get(0).getGoodsSpecificationAttrs()) {
                        attrNames.add(attr.getAttrName());
                    }
                }
                model.addAttribute("attrNames", attrNames);
                // 获取商品图片
                List<CommonImg> imgs = commonImgService.selectImgsByObjIdAndObjType(id, Constants.IMG_GOODS_BANNER);
                model.addAttribute("imgs", imgs);
                // 获取所有一级商品分类
                model.addAttribute("firstCategory", goodsCategoryService.getGoodsCategoryByLevel(1));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        
        return "mall/goodsInfo/goodsInfoDetail";
    }
}
